package com.cn.wanxi.servlet.user;

import com.alibaba.fastjson.JSONObject;
import com.cn.wanxi.model.ResultModel;
import com.cn.wanxi.model.UserModel;
import com.cn.wanxi.service.UserService;
import com.cn.wanxi.service.impl.UserServiceImpl;
import com.cn.wanxi.util.Tool;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/back/user/add")
public class UserAddServlet extends HttpServlet {
    /**
     * doget和dopost的区别？
     * 所有的更新都用post，所有的查询都用get
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //      0.乱码处理
//        req.setCharacterEncoding("UTF-8");
//        resp.setCharacterEncoding("UTF-8");
        //        1.取得页面数据
        String username = req.getParameter("username");
        String address = req.getParameter("address");
        String password = req.getParameter("password");
        String email = req.getParameter("email");
        String phone = req.getParameter("phone");
        String sex = req.getParameter("sex");
        String birthday = req.getParameter("birthday");
        String hobby = req.getParameter("hobby");
//        String[] hh=req.getParameterValues("hobby");
        String enable = req.getParameter("enable");

        //       2. 封装对象
        UserModel userModel = new UserModel();
        userModel.setUsername(username);
        userModel.setPassword(password);
//        try {
//            userModel.setEnable(Integer.parseInt(enable));
//        } catch (Exception e) {
//            e.printStackTrace();
//            userModel.setEnable(-1);
//        }
        userModel.setEnable(Tool.strToInt(enable));
        userModel.setPhone(phone);
        userModel.setSex(sex);
        userModel.setBirthday(Tool.birthday(birthday));
        userModel.setHobby(hobby);
        userModel.setAddress(address);
        userModel.setEmail(email);

//        3.调用服务逻辑层
        UserService userService = new UserServiceImpl();
//       4. 必须要给前端一个返回值,统一的格式
        ResultModel resultModel = userService.add(userModel);
//        5.返回前端
        resp.getWriter().println(JSONObject.toJSONString(resultModel));
//        以后无论是Java和web或者其他语言和web都是用json格式进行转换
//        所以我们需要将Java对象转换为json格式


    }
}
